<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script src="lib/es6-promise.min.js"></script>
    <script src="lib/aliyun-oss-sdk4.13.2.min.js"></script>
    <script src="lib/aliyun-upload-sdk1.3.1.min.js"></script>
</head>
<body>
    文件信息
    <hr />
    <table frame=void width="100%">
        <tr>
            <td>文件名（包含后缀）:</td>
            <td><input type="text" id="videoName" size="20" value=""></td>
            <td>文件标题:</td>
            <td><input type="text" id="title" size="20" value=""></td>
            <td>文件描述:</td>
            <td><input type="text" id="description" size="20" value=""></td>
            <td>文件标签:</td>
            <td><input type="text" id="tags" size="20" value=""></td>
            <td style=""><button type="button" onclick="getUploadInfo()">获得上传信息</button></td>
        </tr>
        </tr>
    </table>
    <hr />


    点播上传配置
    <hr />
    <table frame=void width="100%">
        <tr>
            <td>uploadAuth:</td>
           <td><input type="text" id="uploadAuth" size="20" value=""></td>
            <td>uploadAddress:</td>
            <td><input type="text" id="uploadAddress" size="20" value=""></td>
            <td>videoId:</td>
            <td><input type="text" id="videoId" size="20" value=""></td>
        </tr>
        </tr>
    </table>
    <hr />


    文件管理
    <hr />
    <input type="file" name="file" id="files" multiple/>
    <button type="button" onclick="clearInputFile()">清空继续选择</button>
    <button type="button" onclick="deleteFile()">删除文件</button>
    <input type="text" id="deleteIndex" size="3" value="0">
    <button type="button" onclick="cancelFile()">取消文件</button>
    <input type="text" id="cancelIndex" size="3" value="0">

    <button type="button" onclick="resumeFile()">恢复文件</button>
    <input type="text" id="resumeIndex" size="3" value="0">
    <hr />
    列表管理
    <hr />
    <button type="button" onclick="getList()">获取上传列表</button>
    <button type="button" onclick="clearList()">清理上传列表</button>
    <button type="button" id="goto-play" onclick="gotoPlay(this)" data-playauth="">跳转到视频播放页</button>
    <button type="button" id="getInfo" onclick="getInfo(this)" data-playauth="">获得文件信息</button>

    <hr />


    文件信息
    <hr />
    <table frame=void width="100%">
        <tr>
            <td>文件名（包含后缀）:</td>
            <td><input type="text" id="rvideoName" size="20" value=""></td>
            <td>文件下载地址:</td>
            <td><input type="text" id="download" size="20" value=""></td>
        </tr>
        </tr>
    </table>
    <hr />


    上传管理
    <hr/>
    <button type="button" onclick="start()">开始上传</button>
    <button type="button" onclick="stop()">停止上传</button>
   <!--  <button type="button" onclick="stop()">停止上传</button> -->
    <button type="button" onclick="resumeWithToken()">token过期恢复上传</button>
    <hr />
    <select multiple="multiple" id="textarea" style="position:relative; width:90%; height:450px; vertical-align:top; border:1px solid #cccccc;"></select>
    <button type="button" onclick="clearLog()">清日志</button>

<script>

    var uploader = new AliyunUpload.Vod({
            // 文件上传失败
            'onUploadFailed': function (uploadInfo, code, message) {
                log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
            },
            // 文件上传完成
            'onUploadSucceed': function (uploadInfo) {
                log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
            },
            // 文件上传进度
            'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
                log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + (loadedPercent * 100.00).toFixed(2) + "%");
            },

            onUploadCanceled:function(uploadInfo)
            {
                log("onUploadCanceled:file:" + uploadInfo.file.name);
            },
            // 开始上传
            'onUploadstarted': function (uploadInfo) {
                if(!uploadInfo.videoId)//这个文件没有上传异常
                {
                    //mock 上传凭证，实际产品中需要通过接口获取
                    var uploadAuth = document.getElementById("uploadAuth").value;
                    var uploadAddress = document.getElementById("uploadAddress").value;
                    var videoId = document.getElementById("videoId").value;
                    //实际环境中调用调用点播的获取上传凭证接口
                    //https://help.aliyun.com/document_detail/55407.html?spm=a2c4g.11186623.6.629.CH7i3X
                    //获取上传凭证后，调用setUploadAuthAndAddress
                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
                }
                else//如果videoId有值，根据videoId刷新上传凭证
                {
                    //mock 上传凭证 实际产品中需要通过接口获取
                    var uploadAuth = document.getElementById("uploadAuth").value;
                    var uploadAddress = document.getElementById("uploadAddress").value;
                    //实际环境中调用点播的刷新上传凭证接口，获取凭证
                    //https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
                    //获取上传凭证后，调用setUploadAuthAndAddress
                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
                }

                log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
            }
            ,
            'onUploadEnd':function(uploadInfo){
                log("onUploadEnd: uploaded all the files");
            }
        });

    // 点播上传。每次上传都是独立的鉴权，所以初始化时，不需要设置鉴权
    // 临时账号过期时，在onUploadTokenExpired事件中，用resumeWithToken更新临时账号，上传会续传。
    var selectFile = function (event) {
            var userData = '{"Vod":{"UserData":{"IsShowWaterMark":"false","Priority":"7"}}}';

            for(var i=0; i<event.target.files.length; i++) {
                log("add file: " + event.target.files[i].name);
                uploader.addFile(event.target.files[i], null, null, null, userData);
            }
        };

    document.getElementById("files")
        .addEventListener('change', selectFile);

    var textarea=document.getElementById("textarea");

    function getUploadInfo() {
        var videoName = document.getElementById("videoName").value;
        var title = document.getElementById("title").value;
        var description = document.getElementById("description").value;
        var tags = document.getElementById("tags").value;

        var data = {"videoName":videoName,"title":title,"description":description,"tags":[tags]};

        fetch("/api/vod/get-upload-addr",{
            method: "POST",
            body: JSON.stringify(data),
            headers: {
                "Content-Type": "application/json"
            }
        }).then(function (response) {
            response.json()
                .then(function (resp) {
                    document.getElementById("uploadAuth").value=resp.data.uploadAuth;
                    document.getElementById("uploadAddress").value=resp.data.uploadAddress;
                    document.getElementById("videoId").value=resp.data.videoId;
                    document.getElementById("goto-play").setAttribute("data-playauth",resp.data.videoId);
                    document.getElementById("getInfo").setAttribute("data-playauth",resp.data.videoId);
                })

        })

    }

    function gotoPlay(that) {
        var videoId = that.getAttribute("data-playauth");
        fetch("/api/vod/get-play-addr",{
            method: "POST",
            body: videoId,
            headers: {
                "Content-Type": "application/json"
            }
        }).then(function (response) {
            response.json().then(function (resp) {
                window.location.href = "/player.html?playauth="+resp.data.playAuth+"&cover="+resp.data.videoMeta.coverURL+"&vid="+videoId;
            })
        });
    }
    function getInfo(that) {
        var videoId = that.getAttribute("data-playauth");
        fetch("/api/vod/get-video-info",{
            method: "POST",
            body: videoId,
            headers: {
                "Content-Type": "application/json"
            }
        }).then(function (response) {
            response.json().then(function (resp) {
                document.getElementById("rvideoName").value=resp.data.mezzanine.fileName;
                document.getElementById("download").value=resp.data.mezzanine.fileURL;
            })
        });
    }
    function start() {
        log("start upload.");
        uploader.startUpload();
    }

    function stop() {
        log("stop upload.");
        uploader.stopUpload();
    }

    function resumeWithToken() {
        log("resume upload with token.");
        var uploadAuth = document.getElementById("uploadAuth").value;

        uploader.resumeUploadWithAuth(uploadAuth);

    }

    function clearInputFile()
    {
        var ie = (navigator.appVersion.indexOf("MSIE")!=-1);  
        if( ie ){  
            var file = document.getElementById("files");
            var file2= file.cloneNode(false);  
            file2.addEventListener('change', selectFile);
            file.parentNode.replaceChild(file2,file);  
        }
        else
        {
            document.getElementById("files").value = '';
        }

    }

    function clearList() {
        log("clean upload list.");
        uploader.cleanList();
    }

    function getList() {
        log("get upload list.");
        var list = uploader.listFiles();
        for (var i=0; i<list.length; i++) {
            log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
        }
    }

    function deleteFile() {
        if (document.getElementById("deleteIndex").value) {
            var index = document.getElementById("deleteIndex").value
            log("delete file index:" + index);
            uploader.deleteFile(index);
        }
    }

    function cancelFile() {
        if (document.getElementById("cancelIndex").value) {
            var index = document.getElementById("cancelIndex").value
            log("cancel file index:" + index);
            uploader.cancelFile(index);
        }
    }

    function resumeFile() {
        if (document.getElementById("resumeIndex").value) {
            var index = document.getElementById("resumeIndex").value
            log("resume file index:" + index);
            uploader.resumeFile(index);
        }
    }

    function clearLog() {
        textarea.options.length = 0;
    }

    function log(value) {
        if (!value) {
            return;
        }

        var len = textarea.options.length;
        if (len > 0 && textarea.options[len-1].value.substring(0, 40) == value.substring(0, 40)) {
            //textarea.remove(len-1);
        } else if (len > 25) {
            textarea.remove(0);
        }

        var option=document.createElement("option");
        option.value=value,option.innerHTML=value;
        textarea.appendChild(option);
    }


</script>

</body>
</html>
